#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
修复commits表结构的工具
检查并添加可能缺少的字段
"""

import mysql.connector
from mysql.connector import Error
from utils.logger import sync_logger
from config.db_config import DB_CONFIG

def fix_commits_table():
    """检查并修复commits表结构"""
    sync_logger.log_info("开始检查commits表结构...")
    
    try:
        conn = mysql.connector.connect(**DB_CONFIG)
        cursor = conn.cursor()
        
        # 获取commits表的列信息
        cursor.execute("SHOW COLUMNS FROM commits")
        columns = {column[0] for column in cursor.fetchall()}
        sync_logger.log_info(f"commits表现有字段: {columns}")
        
        # 检查并添加缺失的字段
        missing_fields = []
        
        # 检查created_at字段
        if 'created_at' not in columns:
            missing_fields.append("ADD COLUMN created_at DATETIME")
            sync_logger.log_info("缺少created_at字段，将添加")
        
        # 检查committed_date字段
        if 'committed_date' not in columns:
            missing_fields.append("ADD COLUMN committed_date DATETIME")
            sync_logger.log_info("缺少committed_date字段，将添加")
        
        # 检查stats字段
        if 'stats_additions' not in columns:
            missing_fields.append("ADD COLUMN stats_additions INT DEFAULT 0")
            sync_logger.log_info("缺少stats_additions字段，将添加")
        
        if 'stats_deletions' not in columns:
            missing_fields.append("ADD COLUMN stats_deletions INT DEFAULT 0")
            sync_logger.log_info("缺少stats_deletions字段，将添加")
        
        if 'stats_total' not in columns:
            missing_fields.append("ADD COLUMN stats_total INT DEFAULT 0")
            sync_logger.log_info("缺少stats_total字段，将添加")
        
        # 如果有缺失字段，执行ALTER TABLE语句
        if missing_fields:
            alter_sql = f"ALTER TABLE commits {', '.join(missing_fields)}"
            cursor.execute(alter_sql)
            conn.commit()
            sync_logger.log_info(f"commits表结构修复成功，添加了 {len(missing_fields)} 个字段")
        else:
            sync_logger.log_info("commits表结构完整，无需修复")
        
    except Error as e:
        sync_logger.log_error(f"修复commits表结构时发生错误: {e}")
    finally:
        if conn.is_connected():
            cursor.close()
            conn.close()

if __name__ == "__main__":
    fix_commits_table() 